package com.github.catvod.spider;

import android.text.TextUtils;

import com.github.catvod.crawler.SpiderDebug;
import com.github.catvod.utils.Misc;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.seimicrawler.xpath.JXDocument;
import org.seimicrawler.xpath.JXNode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 适配没有播放列表，只有单集的站点
 *
 * @Author zlliu
 * @Date 2025/8/26
 * @Description
 */
public class XPathV2 extends XPath {

    protected String categoryUrl(String tid, String pg, boolean filter, HashMap<String, String> extend) {
        if (extend != null && !extend.isEmpty()) {
            for (String key : extend.keySet()) {
                String value = extend.get(key);
                if (StringUtils.isNotBlank(value)) {
                    value = value.replace("{catePg}", pg);
                    return rule.getHomeUrl() + "/" + tid + value;
                }
            }
        }
        return getCateUrl(true).replace("{cateId}", tid).replace("{catePg}", pg);
    }

    @Override
    public String detailContent(List<String> ids) {
        try {
            fetchRule();
            String webUrl = getDetailUrl(false).replace("{vid}", ids.get(0));
            String webContent = fetch(webUrl);
            JXDocument doc = JXDocument.create(webContent);
            JXNode vodNode = doc.selNOne(rule.getDetailNode());

            String pic = "", title = "", desc = "", category = "", area = "", year = "", remark = "", director = "", actor = "";

            title = vodNode.selOne(rule.getDetailName()).asString().trim();
            title = rule.getDetailNameR(title);

            pic = vodNode.selOne(rule.getDetailImg()).asString().trim();
            pic = rule.getDetailImgR(pic);
            pic = Misc.fixUrl(webUrl, pic);

            if (StringUtils.isNotBlank(rule.getDetailCate())) {
                try {
                    category = vodNode.selOne(rule.getDetailCate()).asString().trim();
                    category = rule.getDetailCateR(category);
                } catch (Exception e) {
                    SpiderDebug.log(e);
                }
            }
            if (StringUtils.isNotBlank(rule.getDetailYear())) {
                try {
                    year = vodNode.selOne(rule.getDetailYear()).asString().trim();
                    year = rule.getDetailYearR(year);
                } catch (Exception e) {
                    SpiderDebug.log(e);
                }
            }
            if (StringUtils.isNotBlank(rule.getDetailArea())) {
                try {
                    area = vodNode.selOne(rule.getDetailArea()).asString().trim();
                    area = rule.getDetailAreaR(area);
                } catch (Exception e) {
                    SpiderDebug.log(e);
                }
            }
            if (StringUtils.isNotBlank(rule.getDetailMark())) {
                try {
                    remark = vodNode.selOne(rule.getDetailMark()).asString().trim();
                    remark = rule.getDetailMarkR(remark);
                } catch (Exception e) {
                    SpiderDebug.log(e);
                }
            }
            if (StringUtils.isNotBlank(rule.getDetailDirector())) {
                try {
                    director = vodNode.selOne(rule.getDetailDirector()).asString().trim();
                    director = rule.getDetailDirectorR(director);
                } catch (Exception e) {
                    SpiderDebug.log(e);
                }
            }
            if (StringUtils.isNotBlank(rule.getDetailActor())) {
                try {
                    List<JXNode> textNode = vodNode.sel(rule.getDetailActor());
                    actor = textNode.stream().map(JXNode::asString).collect(Collectors.joining("/"));
                    actor = rule.getDetailActorR(actor);
                } catch (Exception e) {
                    SpiderDebug.log(e);
                }
            }
            if (StringUtils.isNotBlank(rule.getDetailDesc())) {
                try {
                    desc = vodNode.selOne(rule.getDetailDesc()).asString().trim();
                    desc = rule.getDetailDescR(desc);
                } catch (Exception e) {
                    SpiderDebug.log(e);
                }
            }

            JSONObject vod = new JSONObject();
            vod.put("vod_id", ids.get(0));
            vod.put("vod_name", title);
            vod.put("vod_pic", pic);
            vod.put("type_name", category);
            vod.put("vod_year", year);
            vod.put("vod_area", area);
            vod.put("vod_remarks", remark);
            vod.put("vod_actor", actor);
            vod.put("vod_director", director);
            vod.put("vod_content", desc);

            ArrayList<String> playFrom = new ArrayList<>();
            playFrom.add(rule.getDetailFromName());

            ArrayList<String> playList = new ArrayList<>();
            List<String> vodItems = new ArrayList<>();
            String name = vodNode.selOne(rule.getDetailUrlName()).asString().trim();
            name = rule.getDetailUrlNameR(name);
            String id = vodNode.selOne(rule.getDetailUrlId()).asString().trim();
            id = rule.getDetailUrlIdR(id);
            vodItems.add(name + "$" + id);
            playList.add(TextUtils.join("#", vodItems));

            // 排除播放列表为空的播放源
            for (int i = playFrom.size() - 1; i >= 0; i--) {
                if (playFrom.get(i).isEmpty()) {
                    playFrom.remove(i);
                }
            }
            for (int i = playList.size() - 1; i >= 0; i--) {
                if (playList.get(i).isEmpty() || i >= playFrom.size()) {
                    playList.remove(i);
                }
            }
            String vod_play_from = TextUtils.join("$$$", playFrom);
            String vod_play_url = TextUtils.join("$$$", playList);
            vod.put("vod_play_from", vod_play_from);
            vod.put("vod_play_url", vod_play_url);

            detailContentExt(webContent, vod);

            JSONObject result = new JSONObject();
            JSONArray list = new JSONArray();
            list.put(vod);
            result.put("list", list);
            return result.toString();
        } catch (Exception e) {
            SpiderDebug.log(e);
        }
        return "";
    }

    @Override
    protected String getPlayUrl(boolean append) {
        return super.getPlayUrl(false);
    }
}